﻿using Lf_VoteSys.Models;
using Lf_VoteSys.Models.Database;
using Lf_VoteSys.Models.service;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;

namespace Lf_VoteSys.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly Lf_VoteSysContext _db;
        //注入jwt服务
        private readonly IJWTService _jwtService;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="jwtService"></param>
        
        public UserController(Lf_VoteSysContext db, IJWTService jwtService)
        {
            _db = db;
            _jwtService = jwtService;
        }
        /// <summary>
        /// 创建Token
        /// </summary>
        /// <param name="UserId"></param>
        /// <returns></returns>
        [HttpGet]
        public string CreateToken(string UserId)
        {
            return _jwtService.CreateToken(UserId);
        }

        /// <summary>
        /// 获取用户信息
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        [Authorize]
        public string UserInfo()
        {
            //获取用户信息
            return Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.Name).Value;
        }
        /// <summary>
        /// 注册接口（用户使用邮箱，密码进行注册，密码需要二次确认）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Register(RegisterRequest request)
        {
            

            //1、两次密码是否一致
            if (request.UserPwd != request.CirUserPwd)
                return "两次密码输入不一致";
            //2、邮箱在数据库是否存在 去数据库查一下有没有这个邮箱
            if (_db.UserBiaos.Any(x => x.UserEmail == request.UserEmail))
                return "邮箱已存在";

            //数字随机字符串
            var salt = new Random().Next(1000, 10000);

            //加入一步  把明文密码  转换成 md5字符串
            var md5 = MD5Helper.MD5Encrypt32(request.UserPwd + salt);

            //3、添加用户到数据库
            var user = new UserBiao
            {
                CreateTime = DateTime.Now,
                UserEmail = request.UserEmail,
                UserPwd = md5,
                Salt= salt.ToString()
            };
            _db.UserBiaos.Add(user);
            //保存更改
            var row = _db.SaveChanges();
            if (row > 0)
                return "注册成功";
            return "注册失败";
        }

        /// <summary>
        /// 登录接口 用户使用邮箱，密码进行登录，登录后可访问需要授权的页面）
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public string Login(LoginRequest request)
        {
            //1、用账号（邮箱）查询用户
            var user = _db.UserBiaos.FirstOrDefault(x => x.UserEmail == request.UserEmail);
            //2、判断用户是否存在
            if (user == null)
                return "用户不存在";

            //3、判断用户密码是否正确
            //                                   输入密码 明文 + 数据库里盐值
            var md5 = MD5Helper.MD5Encrypt32(request.UserPwd + user.Salt);

            //     md5                      明文密码
            if (user.UserPwd != md5)
                return "密码不正确";
            //4、创建token
            return _jwtService.CreateToken( user.UserId.ToString());
        }
        /// <summary>
        /// 获取分类 判断该用户的该分类是否已上传过
        /// </summary>
        /// <param name="fenld"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        
        public string getFenlBiao(int fenld)
        { 
            var UserId = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
            var fenlBiao = _db.FenlBiaos.FirstOrDefault(x => x.UserId == Convert.ToInt32(UserId) && x.Fenld == fenld);

            if (fenlBiao == null)
            {
                return "否";
            }
            else
            {
                return "是";
            }
        }
        /// <summary>
        /// 资料上传接口
        /// </summary>
        /// <param name="ziliao"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public string AddZiliao(ZiliaoBiao ziliao)
        {
            _db.ZiliaoBiaos.Add(ziliao);
            var row = _db.SaveChanges();
            if (row > 0)
                return "上传成功";
            return "上传失败";
        }
        /// <summary>
        /// 审核上传资料接口
        /// </summary>
        /// <param name="ziliaold"></param>
        /// <returns></returns>
        [HttpPost]
        public string getZiliaoBiao(int ziliaold)
        {
            
            var ziliaoId = _db.ZiliaoBiaos.FirstOrDefault(x => x.ZiliaoId == ziliaold);

            if (ziliaoId == null)
            {
                return "未通过审核";
            }
            else
            {
                return "已通过审核";
            }
        }

        /// <summary>
        /// 获取企业详情
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ZiliaoBiao GetZiliaoInfo(int ziliaoId)
        {
            var ziliaoInfo = _db.ZiliaoBiaos.FirstOrDefault(x => x.ZiliaoId == ziliaoId);
            return ziliaoInfo;
        }

        /// <summary>
        /// 用户投票接口
        /// </summary>
        /// <param name="ziliaoId"></param>
        /// <returns></returns>
        [HttpPost]
        [Authorize]
        public string AddTopiao(int ziliaoId)
        {
            var UserId = Response.HttpContext.User.Claims.FirstOrDefault(x => x.Type == ClaimTypes.NameIdentifier).Value;
            var topiao = _db.Topiaos.FirstOrDefault(x => x.UserId == Convert.ToInt32(UserId) && x.ZiliaoId == ziliaoId);
            topiao.Piaosshu += 1;
            _db.Topiaos.Update(topiao);
            var row = _db.SaveChanges();
            if (row > 0)
                return "投票成功";
            return "投票失败";
        }

        
        /// <summary>
        /// 获取投票项目列表接口 
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public GetZiliaoShowResponse GetGoodShow(GetGoodShowRequest request)
        {
            //固定
            var fen = _db.ZiliaoBiaos.Where(x => x.ZiliaoId == request.ZiliaoId);
            //如果传入关键字不为空 查询
            if (!string.IsNullOrEmpty(request.Keyword))
            {
                //模糊查询
                fen = fen.Where(x => x.ZiliaoName.Contains(request.Keyword));
            }
            var total = fen.Count();
            //分页
            var list = fen
                 //排序 分页前一定要排序
                 .OrderByDescending(x => x.ZiliaoId)
                 //跳过n===((pageIndex-1)*pageSize) 条
                 .Skip((request.PageIndex - 1) * request.PageSize)
                 //取x条数据
                 .Take(request.PageSize)
                 .Select(x => new ZiliaoShowModel
                 {
                     ZiliaoId = x.ZiliaoId,
                     Photo = x.Logo,
                     Title = x.ZiliaoName
                 })
                 .ToList();

            var response = new GetZiliaoShowResponse
            {
                List = list,
                Total = total
            };
            return response;
        }
    }
}
